package com.hyy.springbootblog.common.utils;


import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {

    //签名信息
    public static String secret = "oeWWf6KofPvMtRj+RGiOBB59L6A4yG/TwOrVRkGUZZw=";
    public static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));


    //7小时过期
    private static final long expiration=1000 * 60 * 60 * 24 * 7L;

    //1.生成token
    public static String getToken(Map<String, Object> map) {

        return Jwts.builder()
                .setClaims(map)
                .signWith(key)
                .setIssuedAt(new Date())//签发时间
                .setExpiration(new Date(System.currentTimeMillis() +expiration ))
                .compact();
    }


    // 校验token
    public static Claims parseToken(String token) {

        try {
            //jwt解析器 这个解析器自动会补货token空指针异常
            JwtParser build = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build();

            //申明：实际记录的内容
            Claims claims = build.parseClaimsJws(token).getBody();

//            // 打印解析出的 Claims
//            System.out.println("ID: " + claims.get("id"));
//            System.out.println("Name: " + claims.get("name"));
//            System.out.println("Age: " + claims.get("age"));
            return claims;
        } catch (ExpiredJwtException e) {
            // 如果验证失败或解析错误，打印错误信息
            log.error("token令牌已经过期：{}",e.getMessage());
        }catch (SignatureException e) {
            log.error("签名不匹配：{}",e.getMessage());
        }catch (Exception e) {
            log.error("其他解析异常：{}",e.getMessage());
        }
        return null;
    }


    //3.生成key   
    public void getKey() {
        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String enCode = Encoders.BASE64.encode(secretKey.getEncoded());
        System.out.println(enCode);
    }
}

